package com.example.servlet;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.slf4j.Logger;


import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/checkLogin")

public class CheckLoginServlet extends HttpServlet {

    Logger logger = org.slf4j.LoggerFactory.getLogger(CheckLoginServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        HttpSession session = req.getSession(false); // false 表示不要新建session
        if (session != null && session.getAttribute("user") != null) {
            logger.info("将用户名封装成json格式，传递给前端");
            String username = (String) session.getAttribute("user");
            out.write("{\"loggedIn\": true, \"username\": \"" + username + "\"}");
        } else {
            out.write("{\"loggedIn\": false}");
        }
        out.flush();
        out.close();
    }
}
